package com.rose.doorto.footbathdoor.controler;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rose.doorto.common.constant.AuthServerConstant;
import com.rose.doorto.common.constant.Constant;
import com.rose.doorto.footbathdoor.mapper.AddressMapper;
import com.rose.doorto.footbathdoor.pojo.Address;
import com.rose.doorto.footbathdoor.pojo.User;
import com.rose.doorto.footbathdoor.service.AddressService;
import com.rose.doorto.footbathdoor.service.impl.AddressServiceImpl;
import com.rose.doorto.footbathdoor.service.impl.DgtxPlacesServiceImpl;
import com.rose.doorto.footbathdoor.util.PageUtils;
import com.rose.doorto.footbathdoor.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lqc
 * @since 2024-07-11
 */
@Controller
@RequestMapping("/doorto/address")
public class AddressController {

    @Autowired
    private AddressService service;

    @Autowired
    private AddressServiceImpl addressService;

    @Autowired
    private DgtxPlacesServiceImpl dgtxPlacesService;

    @Autowired
    private AddressMapper addressMapper;


    @GetMapping("/your-page")
    public String yourPage(@RequestParam(value = "page", defaultValue = "1") int pageNum,
                           @RequestParam(value = "size", defaultValue = "10") int pageSize,
                           Model model) {
        IPage<Address> pageData = addressService.selectPage(pageNum,pageSize);
        model.addAttribute("pageData", pageData);
        return "/addressList.html";
    }

    /**
     * 分页查询我的收货地址列表
     * @param pageNum
     * @param pageSize
     * @param model
     * @param session
     * @return
     */
    @GetMapping("/addressList")
    public String addressList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") String pageNum,
                              @RequestParam(value = "pageSize", required = false, defaultValue = "5") String pageSize,
                              Model model,
                              HttpSession session){
        Map<String, Object> params = new HashMap<>();
        params.put(Constant.PAGE, pageNum);
        params.put(Constant.LIMIT, pageSize);
        PageUtils page = service.getCurrentAddressList(params, session);
        model.addAttribute("page",page);
        return "/addressList.html";
    }

    @GetMapping("/insert")
    public String toAddPage(){
//        model.addAttribute("dept",dao2.getDepartments());
        return "/insertAddress.html";
    }

    /**
     * 新增收货地址列表
     * @param address
     * @return
     */
    @PostMapping("/insertAddress")
    public String insertAddress(Address address, HttpSession session){
        User attribute = (User) session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
        if (address != null){
            Integer province = Integer.valueOf(address.getProvince());
            Integer city = Integer.valueOf(address.getCity());
            Integer area = Integer.valueOf(address.getCountyTown());
            String provinceName = dgtxPlacesService.getById(province);
            String cityName = dgtxPlacesService.getById(city);
            String areaName = dgtxPlacesService.getById(area);
            address.setProvince(provinceName);
            address.setCity(cityName);
            address.setCountyTown(areaName);
            //TODO 后期处理,从登录信息里获取当前用户id，先写死
            Integer id = attribute.getId();    //当前登录用户ID
            address.setUserId(id);
            int i = service.insertAddress(address);
            if (i == 1){
                return "/addressList.html";
            }else {
                return "添加失败";
            }
        }
        return "redirect:/insertAddress.html";
    }

    /**
     * 设置默认地址
     * @param status
     * @return
     */
    @PostMapping("/updateStatus")
    public String updateStatus(int status){
        int i = service.updateStatus(status);
        if (i == 1){
            return "设置默认地址成功";
        }else {
            return "操作失败";
        }
    }

    /**
     * 获取登录用户的收货地址列表
     * @param userId
     * @return
     */
    @GetMapping("/getAddressByUserId")
    public List<Address> getAddressByUserId(Integer userId){
        //设置分页参数
        Page<Address> page = new Page<>(1, 5);
        //TODO 先写死,userId是从登录用户信息里取出来的,后期在改
        userId = 1;
//        List<Address> addressByUserId = service.getAddressByUserId(page,userId);
//        for (Address address : addressByUserId) {
//            System.out.println(address);
//        }
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        Page<Address> paged = service.page(page, queryWrapper.eq("userId", 1));
        System.out.println(paged);
        return null;
    }

    /**
     * 获取登录用户的收货地址列表
     *
     * @param userId
     * @return
     */
//    @GetMapping("getAddressPage")
//    public Result<Page<Address>> getAddressPage(Integer userId, PageParam pageParam, Model model){
//        userId = 1;
//        Page<Address> addressPage = service.getAddressPage(userId, pageParam);
//        //Result<Page<Address>> success = success(addressPage);
//        List<Address> records = addressPage.getRecords();
//        model.addAttribute("addressPage",records);
//        System.out.println(records+"这是打印的数据======================================================================");
//        return success(addressPage,200,"请求成功");
//    }

    /**
     * 获取用户的收货地址列表
     * @param userId
     * @param pageParam
     * @param model
     * @return
     */
//    @GetMapping("/getAddressPage")
//    public String getAddressPage(Integer userId, PageParam pageParam, Model model){
//        userId = 1;
//        Page<Address> addressPage = service.getAddressPage(userId, pageParam);
//        //Result<Page<Address>> success = success(addressPage);
//        List<Address> records = addressPage.getRecords();
//        model.addAttribute("addressPage",records);
//        System.out.println(records+"这是打印的数据======================================================================");
////        return success(addressPage,200,"请求成功");
//        return "addressList.html";
//    }

    @GetMapping("/getAddressPage")
    public String getAddressPage(@RequestParam Map<String, Object> params,Model model,HttpSession session){
//        User attribute = (User) session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
//        Long id = attribute.getId(); //用户ID
//        params.put("id",id);
        PageUtils page = service.getAddressPage(params);
        System.out.println(page);
        model.addAttribute("addressPage",page);
        return "操作成功";
    }

    @RequestMapping("/list")
    // @RequiresPermissions("ware:waresku:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = service.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 删除收货地址
     * @param id
     * @return
     */
    @DeleteMapping("/delete2")
    public String delete2(@PathVariable("id") String id){
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        boolean remove = service.remove(wrapper);
        if (remove){
            return "删除地址成功";
        }else {
            return "删除地址失败";
        }
    }


    /**
     * 删除收货地址方法2
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable("id") String id){
        int i = service.delete(id);
        if (i > 0){
            return "删除地址成功";
        }else {
            return "删除地址失败";
        }
    }


    @DeleteMapping("/deleteBatch")
    public String deleteBatch(@RequestParam("ids") List<String> ids){
        return service.deleteBatch(ids);
    }


    /**
     * 设置默认收货地址
     * @param session
     * @param id
     * @return
     */
    @GetMapping("/setDefauleAddress/{id}")
    public String setDefauleAddress(HttpSession session, @PathVariable("id") Integer id) {
        User attribute = (User) session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
        Integer userId = Math.toIntExact(attribute.getId());
        Address defaultAddress = addressMapper.getDefaultAddress(userId);  //获取当前用户的默认收货地址列表
        if (defaultAddress == null){
            //当前用户没有设置默认收货地址,直接将你选中的地址设置成默认收货地址
            service.setDefauleAddress(userId,id);
        }else {
            //取消默认地址的设置,将原默认收货地址状态取消
            addressMapper.cancelDefauleAddress(userId,defaultAddress.getId());
            //将新选择的地址设置成默认收货地址
            int i = service.setDefauleAddress(userId, id);
            if (i>=0){
                return "操作成功";
            }else {
                return "操作失败";
            }
        }
        return "/index.html";
    }




















}
